package com.ai.service.made.impl;

import com.ai.common.CommonResponse;
import com.ai.entity.made.ModbusNodeInfo;
import com.ai.entity.made.ModbusServerInfo;
import com.ai.entity.made.page.ModbusServerInfoPage;
import com.ai.mapper.made.ModbusServerInfoMapper;
import com.ai.modbus.ModbusReadRunnable;
import com.ai.model.dto.ModbusServerInfoDto;
import com.ai.opc.OpcThreadPoolExecutor;
import com.ai.service.made.IModbusNodeInfoService;
import com.ai.service.made.IModbusServerInfoService;
import com.ai.util.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiaok
 * @since 2024-11-26
 */
@Service
@Slf4j
public class ModbusServerInfoServiceImpl extends ServiceImpl<ModbusServerInfoMapper, ModbusServerInfo> implements IModbusServerInfoService {

    @Value("${opc.threshold}")
    private  Integer threshold ;

    @Resource
    private IModbusNodeInfoService iModbusNodeInfoService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public CommonResponse<String> add(ModbusServerInfoDto modbusServerInfoDto) {

        ModbusServerInfo modbusServerInfo = new ModbusServerInfo();
        BeanUtils.copyProperties(modbusServerInfoDto,modbusServerInfo);

        modbusServerInfo.setNodeNum(0);
        modbusServerInfo.setCreateUser(SecurityUtils.getLoginUserName());
        modbusServerInfo.setCreateTime(LocalDateTime.now());
        modbusServerInfo.setUpdateUser(SecurityUtils.getLoginUserName());
        modbusServerInfo.setUpdateTime(LocalDateTime.now());

        boolean save = this.save(modbusServerInfo);

        return save?CommonResponse.ok("新增成功"):CommonResponse.error("新增失败");
    }

    @Override
    public CommonResponse<String> delete(String id) {
        //检查该服务下是否有子节点
        long modbusNodeCount = iModbusNodeInfoService.count(new QueryWrapper<ModbusNodeInfo>().eq("modbus_server_id", id));
        if (modbusNodeCount > 0){
            throw  new RuntimeException("modbus下存在节点，删除失败");
        }
        //删除设备
        this.removeById(id);
        return CommonResponse.ok("删除成功");
    }


    @Override
    public CommonResponse<String> edit(ModbusServerInfoDto modbusServerInfoDto) {

        ModbusServerInfo dbModbusServerInfo = this.getById(modbusServerInfoDto.getId());
        dbModbusServerInfo.setIp(modbusServerInfoDto.getIp());
        dbModbusServerInfo.setPort(modbusServerInfoDto.getPort());
        dbModbusServerInfo.setCommunicationModel(modbusServerInfoDto.getCommunicationModel());
        dbModbusServerInfo.setDeviceName(modbusServerInfoDto.getDeviceName());
        dbModbusServerInfo.setUpdateUser(SecurityUtils.getLoginUserName());
        dbModbusServerInfo.setUpdateTime(LocalDateTime.now());

        boolean update = this.updateById(dbModbusServerInfo);

        return update?CommonResponse.ok("修改成功"):CommonResponse.error("修改失败");
    }

    @Override
    public IPage selectByPage(ModbusServerInfoPage page) {

        QueryWrapper<ModbusServerInfo> queryWrapper = page.getQuery(new QueryWrapper<ModbusServerInfo>());
        ModbusServerInfoPage modbusServerInfoPage = this.page(page, queryWrapper);

        return modbusServerInfoPage;
    }

    @Override
    public void readModbusServerNodeInfo() {
        log.info("===========================    读取modbus设备    ===========================");
        List<ModbusServerInfo> modbusServerInfoList = this.list();
        if (!CollectionUtils.isEmpty(modbusServerInfoList)){
            //开始获取各个服务下的节点信息
            for (ModbusServerInfo modbusServerInfo : modbusServerInfoList) {
                List<ModbusNodeInfo> modbusNodeInfoList = iModbusNodeInfoService.list(new QueryWrapper<ModbusNodeInfo>().eq("modbus_server_id", modbusServerInfo.getId()));
                if (!CollectionUtils.isEmpty(modbusNodeInfoList)){
                    OpcThreadPoolExecutor.executorService.submit(new ModbusReadRunnable(modbusServerInfo,modbusNodeInfoList,stringRedisTemplate,threshold));
                }
            }
        }
    }

}
